package se3a04.mcmapster;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class LocalDB {
	
	private static final String DATABASE_NAME = "mcmapster";
	private static final String DATABASE_TABLE = "TOUR";
	private static final int DATABASE_VERSION = 1;
	
	public static final String KEY_ROWID = "_id";
	public static final String KEY_NAME = "tour_name";
	public static final String KEY_TOTALPOI = "totalPOI";
	public static final String KEY_POIs = "POIs";
	
	private DbHelper ourHelper;
	private final Context ourContext;
	private SQLiteDatabase ourDatabase;
	
	
	private static class DbHelper extends SQLiteOpenHelper{
		
		public DbHelper(Context context){
			super(context, DATABASE_NAME,null, DATABASE_VERSION);
			
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
					KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
					KEY_NAME + " TEXT NOT NULL, " +
					KEY_TOTALPOI + " INTEGER NOT NULL, " +
					KEY_POIs + " TEXT NOT NULL);"
					
					
					
					
					);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			
		}
		
	}
	public LocalDB (Context c){
		ourContext = c;
	}
	public LocalDB open(){
		ourHelper = new DbHelper(ourContext);
		ourDatabase = ourHelper.getWritableDatabase();
		return this;
	}
	public void close(){
		ourHelper.close();
	}
	public long createEntry(String name, String totalPOI,String POIs){
		ContentValues cv = new ContentValues();
		cv.put(KEY_NAME, name);
		cv.put(KEY_TOTALPOI, totalPOI);
		cv.put(KEY_POIs, POIs);
		return ourDatabase.insert(DATABASE_NAME, null, cv);
		
		
	}
	public String getTour(String tourName){
		String[] columns = new String[]{KEY_ROWID,KEY_NAME,KEY_TOTALPOI,KEY_POIs};
		Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
		String result = "";
		int iRow = c.getColumnIndex(KEY_ROWID);
		int iName = c.getColumnIndex(KEY_NAME);
		int iTotalPOI = c.getColumnIndex(KEY_TOTALPOI);
		int iPOIs = c.getColumnIndex(KEY_POIs);
		
		for (c.moveToFirst();!c.isAfterLast(); c.moveToNext()){
			if (c.getString(iName) == tourName){
			result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iTotalPOI) + " " + c.getString(iPOIs) + "\n"; 
		
			}
		}
		
		
		return result;
		
		
		
	}
	

}
